﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace OpenHttpServer
{
    /// <summary>
    /// 处理Socket监听逻辑
    /// </summary>
    public class SocketProvider
    {
        
        private static Socket serviceSocketListener; //Socke监听处理请求
        private static IPAddress ListenerIP;
        private static int ListenerPort, Listenerbacklog;
        private static CallBack cbfun = null;
        public static int MaxPOSTSize = 50 * 1024 * 1024; // 50MB
        public delegate void CallBack(Socket socket, byte[] bytes);

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="cb">接收数据回调函数</param>
        /// <param name="ipAddress">监听的IP地址，可以设置NULL</param>
        /// <param name="port">监听的端口</param>
        /// <param name="backlog">列队深度</param>
        public static void Init(CallBack cb, IPAddress ipAddress, int port = 80, int backlog = 1024)
        {
            cbfun = cb;
            ListenerIP = (ipAddress == null) ? IPAddress.Any : ipAddress;
            ListenerPort = port;
            Listenerbacklog = backlog;
            Listener();
        }


        /// <summary>
        /// 开启Socket监听
        /// </summary>
        private static void Listener()
        {
            serviceSocketListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serviceSocketListener.Bind(new IPEndPoint(ListenerIP, ListenerPort)); //IP和端口配置
            serviceSocketListener.Listen(Listenerbacklog);
            Thread handleSocket = new Thread(new ThreadStart(HandleSocket));
            handleSocket.Start();
        }

        /// <summary>
        /// 监听链接
        /// </summary>
        private static void HandleSocket()
        {
            while (true)
            {
                try
                {
                    Socket currSocket = serviceSocketListener.Accept();  //为新建连接创建新的 System.Net.Sockets.Socket
                    Thread processThread = new Thread(new ParameterizedThreadStart(ProcessSocket));
                    processThread.Start(currSocket);
                }
                catch { }
            }
        }

        /// <summary>
        /// 处理Socket信息
        /// </summary>
        /// <param name="obj">新建连接创建新Socket对象</param>
        private static void ProcessSocket(object obj)
        {
            Socket currSocket = (Socket)obj;
            try
            {
                byte[] recvBytess = new byte[MaxPOSTSize];
                int recbytes;
                recbytes = currSocket.Receive(recvBytess, recvBytess.Length, 0);
                if (recbytes > 0)
                {
                    if (cbfun != null)
                    {
                        cbfun.Invoke(currSocket, recvBytess);
                    }
                    //var contentStr = Encoding.UTF8.GetString(recvBytess, 0, recbytes);
                   
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("error:{0}", ex.Message);
                //Console.WriteLine("写Error日志" + ex.Message);
            }
        }
    }
}